import { service, crudParamsSerializer } from '@/utils/request'
import { CreateQueryParams } from '@nestjsx/crud-request'
import { Track } from './track.dto'

export const defaultTrackData: Partial<Track> = {}

export function getTracks (params?: CreateQueryParams) {
  return service.get<Track[]>(
    '/resources/tracks',
    {
      params,
      paramsSerializer: crudParamsSerializer
    }
  )
}

export function getTrackById (id: number | string, params?: CreateQueryParams) {
  return service.get<Track>(
    `/resources/tracks/${id}`,
    {
      params,
      paramsSerializer: crudParamsSerializer
    }
  )
}

export function createTrack (dto: Partial<Track>, params?: CreateQueryParams) {
  const data = new FormData()
  if (dto.tag) { data.append('tag', dto.tag) }
  if (dto.file instanceof Blob) { data.append('file', dto.file) }
  if (dto.uploadedByUser) { data.append('uploadedByUser', JSON.stringify(dto.uploadedByUser)) }
  if (dto.relatedSong) { data.append('relatedSong', JSON.stringify(dto.relatedSong)) }
  return service.post<Track>(
    '/resources/tracks',
    data,
    {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      params,
      paramsSerializer: crudParamsSerializer
    }
  )
}
